<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import ElementPlus from 'element-plus'
import EditAdministrator from './EditAdministrator.vue'
import DetailAdministrator from './DetailAdministrator.vue'
import { getAdmindata, getAdmindatalike, deladmin, adminResetPassword, editaccountNonLocked } from '../../api/api'
import data from "@/untils/address/states.json"

let total = ref(0)
let page = ref(1)
let pageSize = ref(10)
import { Decrypt, Encrypt } from '../../untils/passjs/security'
onMounted(() => {
    getAdmin()
})
// 定义的头部输入框的数据
let topdata = ref({
    nickname: "",
    phone: "",
    accountNonLocked: null,
    enabled: null
})
// 表格数据
let tableData = ref([])
// 获取管理员管理的数据
async function getAdmin() {
    try {
        let data = await getAdmindata(page.value, pageSize.value)
        if (data.code == 200) {
            total.value = data.total
            tableData.value = data.rows
        }
    } catch (error) {
        console.log(error);

    }
}
// 渲染状态的显示
let switchFlag = (flag) => {
    return flag == 0 ? true : false;
}
async function switchchange(userId, accountNonLocked) {
    if (accountNonLocked == 0) {
        accountNonLocked = 1
    } else {
        accountNonLocked = 0
    }
    try {
        let res = await editaccountNonLocked({ userId: userId, accountNonLocked: accountNonLocked })
        if (res.code == 200) {
            getAdmin()
        }
    } catch (error) {
        console.log(error);
    }
}
async function switchchangeenabled(userId, enabled) {
    if (enabled == 0) {
        enabled = 1
    } else {
        enabled = 0
    }
    try {
        let res = await editaccountNonLocked({ userId: userId, enabled: enabled })
        if (res.code == 200) {
            ElMessage.success(res.msg)
            getAdmin()
        }
    } catch (error) {
        console.log(error);
    }
}
// 删除
let dianjiid = ref(0)
const dialogVisible = ref(false)
function del(val) {
    dianjiid.value = val.userId
    dialogVisible.value = true
}
async function yesdel() {
    dialogVisible.value = false
    try {
        let res = await deladmin(dianjiid.value);
        if (res.code == 200) {
            ElMessage.success(res.msg)
            getAdmin()
        }
    } catch (error) {
        console.log(error);
    }
}
// 遮罩层
let dialogFormVisible = ref(false)
let changeType = ref("")

const currentUser = ref({})
const passwordVisible = ref(false)
let dialogFormVisibleDetail = ref(false)

function openResetPasswordDialog(user) {
    currentUser.value = user
    passwordVisible.value = true
}

const resetForm = ref({
    newpass: ''
})

async function reactpass(row) {
    passwordVisible.value = false
    if (!resetForm.value.newpass) {
        return
    }
    let requestdata =
    {
        userId: row.userId,
        password: resetForm.value.newpass
    }
    try {
        let res = await adminResetPassword(Encrypt(JSON.stringify(requestdata)))
        if (res.code == 200) {
            ElMessage.success(res.msg)
            resetForm.value.newpass = ""
            getAdmin()
        }
    } catch (error) {
        console.log(error);

    }
}
const resetFormRef = ref(null)
const rulesobj = {
    newpass: [
        {
            required: true,
            message: 'Please input a password',
            trigger: 'blur'
        },
        {
            pattern: /^(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])[A-Za-z\d!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,16}$/,
            message: 'requires a combination of 8-16 letters or numbers',
            trigger: 'blur'
        }
    ]
}
//  传递参数
let formlist = reactive({})
function add() {
    Object.assign(formlist, {
        username: "",
        nickname: "",
        password: "",
        phone: "",
        email: "",
        gender: 0,
        area: "",
        contry: "",
        addresszhou: "",
        account: "",
        userLevel: 1,
        type: "新增",
        roleName: [],
        phoneAreaCode: ''
    })
    console.log(formlist);
    dialogFormVisible.value = true
    console.log("新增操作");
    changeType.value = 'add'
}
function edit(index, row) {
    let arr = []
    if (row.roles !== null) {
        row.roles.forEach(item => {
            arr.push(item.roleId)
        })
    }
    Object.assign(formlist, {
        userId: row.userId,
        nickname: row.nickname,
        email: row.email,
        phone: row.phone,
        gender: row.gender,
        area: row.area,
        contry: "",
        addresszhou: "",
        account: row.address,
        userLevel: row.userLevel,
        type: "修改",
        roleName: arr,
        roleoption: row.roles,
        phoneAreaCode: row.phoneAreaCode
    })
    data.data.forEach(country => {
        if (country.state_code == row.area.split("/")[0]) {
            formlist.contry = country.name;
            country.states.forEach(st => {
                if (st.state_code == row.area.split("/")[1]) {
                    formlist.addresszhou = st.name;
                }
            })
        }
    });
    console.log(formlist);
    changeType.value = "update"
    dialogFormVisible.value = true
}
function closechange() {
    dialogFormVisible.value = false
    getAdmin()
}
let isSearching = ref(false);
async function adminlike() {
    console.log("模糊查询操作");
    isSearching.value = true;
    let { nickname, phone, accountNonLocked, enabled } = topdata.value
    try {
        let res = await getAdmindatalike(nickname, phone, accountNonLocked, enabled, page.value, pageSize.value)
        if (res.code == 200) {
            tableData.value = res.rows
            if (res.rows.length == 0) {
                return;
            }
            total.value = res.total
        }
    } catch (error) {
        console.log(error);

    }
}
function cancel() {
    console.log("重置操作");
    isSearching.value = false;
    topdata.value = {
        nickname: "",
        phone: "",
        accountNonLocked: "",
        enabled: ""
    }
    page.value = 1
    getAdmin()
}
async function getCurrentPage(e) {
    console.log("获取当前页", e);
    page.value = e
    if (isSearching.value) {
        try {
            await adminlike()
        } catch (error) {
            console.log(error);
        }
    } else {
        getAdmin()
    }
}
function detailfun(row) {
    let arr = []
    if (row.roles !== null) {
        row.roles.forEach(item => {
            arr.push(item.roleId)
        })
    }
    Object.assign(formlist, {
        username: row.username,
        userId: row.userId,
        nickname: row.nickname,
        email: row.email,
        phone: row.phone,
        gender: row.gender,
        area: row.area,
        contry: "",
        addresszhou: "",
        account: row.address,
        userLevel: row.userLevel,
        type: "修改",
        roleName: arr,
        roleoption: row.role,
        roles: row.roles,
        phoneAreaCode: row.phoneAreaCode
    })
    data.data.forEach(country => {
        if (country.state_code == row.area.split("/")[0]) {
            formlist.contry = country.name;
            country.states.forEach(st => {
                if (st.state_code == row.area.split("/")[1]) {
                    formlist.addresszhou = st.name;
                }
            })
        }
    });
    console.log(formlist);
    changeType.value = "detail"
    dialogFormVisibleDetail.value = true
}
function closeDeatilfun() {
    dialogFormVisibleDetail.value = false
    getAdmin()
}
const hasPermission = (permission) => {
    const permissions = JSON.parse(localStorage.getItem("userdetail"))?.auths || [];
    if (permissions[0] === '*:*:*') {
        return true; 
    }
    return permissions.includes(permission);
};
</script>

<template>
    <div class="administrator">
        <div class="administratorbas">
            <div class="top">
                <span>administrators</span>
            </div>
            <div class="cont">
                <div class="one">
                    <!-- 输入用户昵称 -->
                    <div class="select">
                        <el-input v-model="topdata.nickname" class="inp" style="width: 180px"
                            placeholder="Enter user nickname">
                            <template #prefix>
                                <el-icon class="el-input__icon">
                                    <search />
                                </el-icon>
                            </template>
                        </el-input>
                    </div>
                    <!-- 输入联系方式 -->
                    <div class="select">
                        <el-input v-model="topdata.phone" class="inp" style="width: 220px"
                            placeholder="Enter contact information">
                            <template #prefix>
                                <el-icon class="el-input__icon">
                                    <search />
                                </el-icon>
                            </template>
                        </el-input>
                    </div>
                    <!-- 锁状态 -->
                    <div class="select">
                        <el-select style="width: 180px" placeholder="Lock status" v-model="topdata.accountNonLocked">
                            <el-option label="Enable" :value="0" />
                            <el-option label="Disable" :value="1" />
                        </el-select>
                    </div>
                    <!-- 启用状态 -->
                    <div class="select">
                        <el-select style="width: 180px" placeholder="Enable status" v-model="topdata.enabled">
                            <el-option label="Enable" :value="0" />
                            <el-option label="Disable" :value="1" />
                        </el-select>
                    </div>
                    <el-button type="primary" @click="adminlike">query</el-button>
                    <el-button type="primary" @click="cancel">reset</el-button>
                </div>
                <div class="exp" v-if="hasPermission('user:admin:add')">
                    <div class="export-excel">
                        <el-button style="width: 160px" type="primary" @click="add()">
                            <el-icon>
                                <FolderAdd />
                            </el-icon>Add Administrator
                        </el-button>
                    </div>
                </div>
                <div class="tab" v-if="hasPermission('user:admin:query')">
                    <el-table stripe :data="tableData" @selection-change="check()" style="width: 100%;" :fit="true">
                        <el-table-column width="55">
                            <!-- :empty-text="!permissionquery ? '暂无权限查看' : 'NotData'" -->
                            <!-- <template #default="scope" @click="check">

                     </template> -->
                        </el-table-column>
                        <el-table-column property="username" label="name" />
                        <el-table-column property="nickname" label="nickname" />
                        <el-table-column property="phone" label="cell-phone number">
                            <template #default="scope">
                                {{ scope.row.phoneAreaCode ? `+${scope.row.phoneAreaCode} ${scope.row.phone}` :
                                    `${scope.row.phone}` }}
                            </template>
                        </el-table-column>
                        <el-table-column property="email" label="email" />
                        <el-table-column property="gender" label="gender">
                            <template #default="scope">
                                <span>{{ scope.row.gender == 1 ? 'male' : 'female' }}</span>
                            </template>
                        </el-table-column>

                        <el-table-column property="accountNonLocked" label="Lock status">
                            <template #default="scope">
                                <template v-if="scope.row.optStatus">
                                    <el-switch :modelValue="switchFlag(scope.row.accountNonLocked)" active-text="enable"
                                        inline-prompt inactive-text="disable"
                                        @click="switchchange(scope.row.userId, scope.row.accountNonLocked)"
                                        class="el-switch">
                                    </el-switch>
                                </template> 
                                <template v-else>
                                    {{ scope.row.accountNonLocked ? 'disable' : 'enable' }}
                                </template>
                            </template>
                        </el-table-column>
                        <el-table-column property="enabled" label="Enable status">
                            <template #default="scope">
                                <template v-if="scope.row.optStatus">
                                    <el-switch :modelValue="switchFlag(scope.row.enabled)" active-text="enable"
                                        inline-prompt inactive-text="disable"
                                        @click="switchchangeenabled(scope.row.userId, scope.row.enabled)"
                                        class="el-switch">
                                    </el-switch>
                                </template>
                                <template v-else>
                                    {{ scope.row.enabled ? 'disable' : 'enable' }}
                                </template>

                            </template>
                        </el-table-column>
                        <el-table-column property="userLevel" label="level">
                            <template #default="scope">
                                <span>{{ {
                                    0: 'T0', 1: 'T1', 2: 'T2', 3: 'T3', 4: 'T4', 5:
                                        'T5'
                                }[scope.row.userLevel] }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column property="operate" label="operate" width="300">
                            <template #default="scope">
                                <span class="more-button" @click="detailfun(scope.row)" style="cursor: pointer;">
                                    detail
                                </span>
                                <span class="more-button" @click="edit(scope.$index, scope.row)"
                                    style="cursor: pointer;"
                                    v-if="scope.row.optStatus && hasPermission('user:admin:edit')">
                                    edit
                                </span>

                                <span class="more-button" @click="del(scope.row)" style="cursor: pointer;"
                                    v-if="scope.row.optStatus && hasPermission('user:admin:remove')">
                                    delete
                                </span>
                                <!-- <el-button type="primary" plain @click="edit(scope.$index, scope.row)">修改</el-button> -->
                                <!-- <el-button type="danger" plain @click=del(scope.row)>删除</el-button> -->
                                <!-- 添加“更多”按钮及下拉菜单 -->
                                <el-dropdown style="cursor: pointer;" v-if="scope.row.optStatus">
                                    <span class="more-button">
                                        more
                                        <el-icon class="el-icon--right"><arrow-down /></el-icon>
                                    </span>
                                    <template #dropdown>
                                        <el-dropdown-menu v-if="hasPermission('user:admin:resetPassword')">
                                            <!-- <el-dropdown-item command="resetPassword"
                                                @click="resetPassword">重置密码</el-dropdown-item> -->

                                            <el-dropdown-item command="resetPassword"
                                                @click="openResetPasswordDialog(scope.row)">
                                                Reset Password
                                            </el-dropdown-item>

                                            <!-- <el-dropdown-item command="viewDetails">查看详情</el-dropdown-item> -->
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>

                            </template>

                        </el-table-column>
                    </el-table>
                    <div style="display: flex;justify-content: end;align-items: center; margin-top: 25px">
                        <el-pagination background layout="prev, pager, next" :page-count="Math.ceil(total / pageSize)"
                            style="text-align: end;" :current-page='page' @current-change="getCurrentPage" />
                    </div>
                    <el-dialog v-model="passwordVisible" title="reset password" width="500" modal-class="custom-modal"
                        @close="passwordVisible = false">
                        <span>please enter {{ currentUser.username }} new password:</span>
                        <!-- 使用 currentUser -->
                        <br>
                        <el-form :model="resetForm" :rules="rulesobj" ref="resetFormRef" @submit.prevent>
                            <el-form-item label="" prop="newpass">
                                <el-input v-model="resetForm.newpass" type="password" maxlength="16" minlength="8"
                                    auto-complete="off" placeholder="password"></el-input>
                            </el-form-item>
                        </el-form>
                        <template #footer>
                            <div class="dialog-footer">
                                <el-button @click="passwordVisible = false">cancel</el-button>
                                <el-button type="primary" @click="reactpass(scope.row)">sure</el-button>
                            </div>
                        </template>
                    </el-dialog>
                    <el-dialog v-model="dialogVisible" title="delete" width="500">
                        <span>Are you sure you want to delete it</span>
                        <template #footer>
                            <div class="dialog-footer">
                                <el-button @click="dialogVisible = false">cancel</el-button>
                                <el-button type="primary" @click="yesdel()">
                                    sure
                                </el-button>
                            </div>
                        </template>
                    </el-dialog>
                </div>
                <EditAdministrator :dialogFormVisible="dialogFormVisible" :changeType="changeType"
                    v-model:formlist="formlist" @close="closechange"></EditAdministrator>
                <DetailAdministrator :dialogFormVisibleDetail="dialogFormVisibleDetail" @closeDeatil="closeDeatilfun"
                    v-model:formlist="formlist">
                </DetailAdministrator>
            </div>
        </div>
    </div>
</template>
<style lang="scss" scoped>
.administrator {
    padding: 15px;
    background-color: #eff1f4;

    .administratorbas {
        background-color: #fff;
        width: 100%;
        height: 88vh;
        border-radius: 10px 10px 0 0;

        .top {
            height: 50px;
            background-color: #f9f9f9;
            border-radius: 10px 10px 0 0;
            font-size: 20px;
            font-weight: bold;
            overflow: hidden;
            border-bottom: 1px solid #f1eded;

            span {
                display: block;
                margin: 10px 0 0 15px;
            }
        }

        .cont {
            // .one {
            //     margin: 10px;
            //     display: flex;
            //     padding: 10px;

            //     div {
            //         margin-right: 20px;
            //     }
            // }
            .one {
                margin: 10px;
                display: flex;
                flex-wrap: wrap;
                gap: 12px;
                align-items: center;
                padding: 10px;
            }

            .select {
                display: flex;
                align-items: center;
            }

            .exp {
                .export-excel {
                    margin-left: 20px;
                }
            }

            .tab {
                margin-top: 20px;
                width: 100%;
                position: relative;
                min-height: 300px;

                .el-table {
                    --el-table-header-bg-color: #fafafa;
                }

                .el-switch {
                    --el-switch-on-color: #45d585;
                }

                .more-button {
                    margin-left: 8px;
                    margin-top: 3px;
                    /* 为“更多”按钮添加左边距 */
                    color: #409EFF;
                    outline: none;

                    /* Element Plus 主题色 */
                    &:hover {
                        color: #66b1ff;

                        /* 鼠标悬停时的颜色 */
                    }
                }
            }
        }
    }

    /* 如果使用 scoped，需要添加 ::v-deep */
    ::v-deep .custom-modal {
        background-color: rgba(0, 0, 0, 0.5);
        /* 设置弹窗背景颜色为半透明 */
    }

    /* 或者更精确的定位 */
    ::v-deep .custom-modal .el-overlay {
        background-color: rgba(0, 0, 0, 0.8);
    }
}
</style>